import Mn from 'backbone.marionette';

import BaseExpenseView from "./BaseExpenseView.js";
import CheckboxWidget from '../../widgets/CheckboxWidget.js';

import { formatAmount } from '../../math.js';
import { formatPaymentDate } from '../../date.js';

const template = require('./templates/SelectableExpenseItemView.mustache');

const SelectableExpenseItemView = BaseExpenseView.extend({
    tagName: 'tr',
    template: template,
    regions: {
        td_action: 'td.action',
        businessLink: '.business-link',
    },
    modelEvents: {
        'change:selected': 'render', // ??
    },
    childViewEvents: {
        'finish': "onChange"
    },
    initialize(){
        this.targetFile = this.getOption('targetFile');
    },
    onRender(){
        if (this.model.get('customer_id')) {
            // Avoid displaying « rien » if there is no linked customer
            SelectableExpenseItemView.__super__.onRender.apply(this);
        }
        let widget = new CheckboxWidget({
            field_name: 'check',
            toggle: false,
            ariaLabel: 'Sélectionner cette ligne',
            value: this.model.isFileLinked(this.targetFile),
            true_val: true,
            false_val: false,
        });

        this.showChildView('td_action', widget);
    },
    onChange(field_name, value){
        if (value === true) {
            this.model.linkToFile(this.targetFile);
        } else {
            this.model.unlinkFromFile(this.targetFile);
        }
        this.model.save(
            {files: this.model.get('files')},
            {patch: true},
        );
    },
    templateContext(){
        return {
            date: formatPaymentDate(this.model.get('date')),
            is_achat: this.isAchat(),
            has_tva_on_margin: this.model.hasTvaOnMargin(),
            type_label: this.model.getTypeLabel(),
            ttc_label: formatAmount(this.model.total()),
            ht_label: formatAmount(this.model.get('ht')),
            tva_label: formatAmount(this.model.get('tva')),
        };
    },
});
export default SelectableExpenseItemView;
